/**
 * 主应用逻辑
 * 提供全局应用状态管理和通用功能
 */

// 全局应用状态
const AppState = {
    currentGroup: null,
    currentDay: 1,
    isInitialized: false,
    sortOrder: 'asc' // 'asc' | 'desc'
};

/**
 * 应用初始化
 */
async function initApp() {
    try {
        // 检查浏览器支持
        if (!isIndexedDBSupported()) {
            showMessage('您的浏览器不支持IndexedDB，请使用现代浏览器', 'error', 5000);
            return false;
        }

        // 初始化数据库
        await initDatabase();
        
        // 设置应用状态
        AppState.isInitialized = true;
        
        console.log('应用初始化成功');
        return true;
    } catch (error) {
        console.error('应用初始化失败:', error);
        showMessage('应用初始化失败: ' + error.message, 'error', 5000);
        return false;
    }
}

/**
 * 获取当前组信息
 * @returns {Object|null} 当前组信息
 */
function getCurrentGroup() {
    return AppState.currentGroup;
}

/**
 * 设置当前组
 * @param {Object} group - 组信息
 */
function setCurrentGroup(group) {
    AppState.currentGroup = group;
}

/**
 * 获取当前天数
 * @returns {number} 当前天数
 */
function getCurrentDay() {
    return AppState.currentDay;
}

/**
 * 设置当前天数
 * @param {number} day - 天数
 */
function setCurrentDay(day) {
    AppState.currentDay = day;
}

/**
 * 计算复习日期
 * @param {number} startDay - 开始天数
 * @param {Array} reviewDays - 复习天数数组
 * @returns {Array} 复习日期数组
 */
function calculateReviewDays(startDay, reviewDays = [1, 2, 4, 7, 14, 21, 28, 50]) {
    return reviewDays.map(day => startDay + day - 1);
}

/**
 * 检查某天是否需要复习
 * @param {number} memoryDay - 记忆内容的天数
 * @param {number} currentDay - 当前天数
 * @param {Array} reviewDays - 复习天数数组
 * @returns {boolean} 是否需要复习
 */
function shouldReview(memoryDay, currentDay, reviewDays = [1, 2, 4, 7, 14, 21, 28, 50]) {
    // 如果是当天新增的内容
    if (memoryDay === currentDay) {
        return true;
    }
    
    // 检查是否在复习日期内
    const daysSinceMemory = currentDay - memoryDay + 1;
    return reviewDays.includes(daysSinceMemory);
}

/**
 * 获取今日需要记忆的内容
 * @param {number} groupId - 组ID
 * @param {number} currentDay - 当前天数
 * @returns {Promise<Array>} 今日记忆内容
 */
async function getTodayMemories(groupId, currentDay) {
    try {
        const allMemories = await db.getMemoriesByGroup(groupId);
        
        // 筛选今日需要记忆的内容
        return allMemories.filter(memory => {
            return shouldReview(memory.day, currentDay, memory.reviewDays);
        });
    } catch (error) {
        console.error('获取今日记忆内容失败:', error);
        showMessage('获取今日记忆内容失败', 'error');
        return [];
    }
}

/**
 * 创建新组
 * @param {string} groupName - 组名
 * @param {string} color - 颜色
 * @returns {Promise<number>} 新组ID
 */
async function createNewGroup(groupName, color = null) {
    try {
        // 验证组名
        const validation = validateGroupData({ name: groupName });
        if (!validation.valid) {
            showMessage(validation.message, 'error');
            return null;
        }

        // 生成颜色
        const groupColor = color || generateRandomColor();

        // 创建组
        const groupData = {
            name: groupName.trim(),
            color: groupColor,
            createTime: getCurrentDateISO()
        };

        const groupId = await db.addGroup(groupData);
        
        // 为新组创建50个空记忆槽位
        for (let day = 1; day <= 50; day++) {
            await db.addMemory({
                groupId: groupId,
                day: day,
                hint: '',
                content: '',
                reviewDays: [1, 2, 4, 7, 14, 21, 28, 50]
            });
        }

        showMessage(`组"${groupName}"创建成功`, 'success');
        return groupId;
    } catch (error) {
        console.error('创建组失败:', error);
        showMessage('创建组失败: ' + error.message, 'error');
        return null;
    }
}

/**
 * 添加记忆内容
 * @param {number} groupId - 组ID
 * @param {number} day - 天数
 * @param {string} hint - 记忆提示
 * @param {string} content - 记忆内容
 * @returns {Promise<boolean>} 是否添加成功
 */
async function addMemoryContent(groupId, day, hint, content) {
    try {
        // 验证数据
        const validation = validateMemoryData({
            groupId: groupId,
            day: day,
            hint: hint,
            content: content
        });
        
        if (!validation.valid) {
            showMessage(validation.message, 'error');
            return false;
        }

        // 检查是否已存在该天的记忆内容
        const existingMemory = await db.getMemoryByGroupAndDay(groupId, day);
        if (existingMemory && existingMemory.hint && existingMemory.content) {
            showMessage(`第${day}天已有记忆内容，请先编辑或删除现有内容`, 'warning');
            return false;
        }

        // 添加或更新记忆内容
        if (existingMemory) {
            await db.updateMemory(existingMemory.id, {
                hint: hint.trim(),
                content: content.trim()
            });
        } else {
            await db.addMemory({
                groupId: groupId,
                day: day,
                hint: hint.trim(),
                content: content.trim(),
                reviewDays: [1, 2, 4, 7, 14, 21, 28, 50]
            });
        }

        showMessage('记忆内容添加成功', 'success');
        return true;
    } catch (error) {
        console.error('添加记忆内容失败:', error);
        showMessage('添加记忆内容失败: ' + error.message, 'error');
        return false;
    }
}

/**
 * 更新记忆内容
 * @param {number} memoryId - 记忆内容ID
 * @param {Object} updateData - 更新数据
 * @returns {Promise<boolean>} 是否更新成功
 */
async function updateMemoryContent(memoryId, updateData) {
    try {
        await db.updateMemory(memoryId, updateData);
        showMessage('记忆内容更新成功', 'success');
        return true;
    } catch (error) {
        console.error('更新记忆内容失败:', error);
        showMessage('更新记忆内容失败: ' + error.message, 'error');
        return false;
    }
}

/**
 * 删除记忆内容
 * @param {number} memoryId - 记忆内容ID
 * @returns {Promise<boolean>} 是否删除成功
 */
async function deleteMemoryContent(memoryId) {
    try {
        await db.deleteMemory(memoryId);
        showMessage('记忆内容删除成功', 'success');
        return true;
    } catch (error) {
        console.error('删除记忆内容失败:', error);
        showMessage('删除记忆内容失败: ' + error.message, 'error');
        return false;
    }
}

/**
 * 导出组数据
 * @param {number} groupId - 组ID
 * @returns {Promise<boolean>} 是否导出成功
 */
async function exportGroupData(groupId) {
    try {
        const group = await db.getGroup(groupId);
        const memories = await db.getMemoriesByGroup(groupId);
        
        const exportData = {
            group: group,
            memories: memories,
            exportTime: getCurrentDateISO(),
            version: '1.0'
        };

        const filename = `${group.name}-记忆数据.json`;
        exportToJSON(exportData, filename);
        
        showMessage('数据导出成功', 'success');
        return true;
    } catch (error) {
        console.error('导出数据失败:', error);
        showMessage('导出数据失败: ' + error.message, 'error');
        return false;
    }
}

/**
 * 导入组数据
 * @param {File} file - JSON文件
 * @returns {Promise<boolean>} 是否导入成功
 */
async function importGroupData(file) {
    try {
        const data = await importFromJSON(file);
        
        if (!data.group || !data.memories) {
            showMessage('数据格式错误', 'error');
            return false;
        }

        // 创建新组
        const groupData = {
            name: data.group.name + ' (导入)',
            color: data.group.color,
            createTime: getCurrentDateISO()
        };

        const groupId = await db.addGroup(groupData);

        // 导入记忆内容
        for (const memory of data.memories) {
            await db.addMemory({
                groupId: groupId,
                day: memory.day,
                hint: memory.hint,
                content: memory.content,
                reviewDays: memory.reviewDays || [1, 2, 4, 7, 14, 21, 28, 50]
            });
        }

        showMessage('数据导入成功', 'success');
        return true;
    } catch (error) {
        console.error('导入数据失败:', error);
        showMessage('导入数据失败: ' + error.message, 'error');
        return false;
    }
}

/**
 * 获取应用统计信息
 * @returns {Promise<Object>} 统计信息
 */
async function getAppStats() {
    try {
        const groups = await db.getAllGroups();
        const totalGroups = groups.length;
        
        let totalMemories = 0;
        let completedMemories = 0;
        
        for (const group of groups) {
            const memories = await db.getMemoriesByGroup(group.id);
            totalMemories += memories.length;
            completedMemories += memories.filter(m => m.hint && m.content).length;
        }

        return {
            totalGroups: totalGroups,
            totalMemories: totalMemories,
            completedMemories: completedMemories,
            completionRate: totalMemories > 0 ? (completedMemories / totalMemories * 100).toFixed(1) : 0
        };
    } catch (error) {
        console.error('获取统计信息失败:', error);
        return {
            totalGroups: 0,
            totalMemories: 0,
            completedMemories: 0,
            completionRate: 0
        };
    }
}

/**
 * 页面加载完成后的初始化
 */
document.addEventListener('DOMContentLoaded', async function() {
    // 检查是否在正确的页面
    const currentPage = window.location.pathname.split('/').pop();
    
    // 如果不是启动页，需要初始化应用
    if (currentPage !== 'index.html' && currentPage !== '') {
        const initialized = await initApp();
        if (!initialized) {
            // 如果初始化失败，跳转到启动页
            window.location.href = 'index.html';
        }
    }
});

// 导出全局函数
window.AppState = AppState;
window.initApp = initApp;
window.getCurrentGroup = getCurrentGroup;
window.setCurrentGroup = setCurrentGroup;
window.getCurrentDay = getCurrentDay;
window.setCurrentDay = setCurrentDay;
window.calculateReviewDays = calculateReviewDays;
window.shouldReview = shouldReview;
window.getTodayMemories = getTodayMemories;
window.createNewGroup = createNewGroup;
window.addMemoryContent = addMemoryContent;
window.updateMemoryContent = updateMemoryContent;
window.deleteMemoryContent = deleteMemoryContent;
window.exportGroupData = exportGroupData;
window.importGroupData = importGroupData;
window.getAppStats = getAppStats;
